package cn.sytton.taffecloud.common.db.datasource;

import cn.sytton.taffecloud.common.db.mapper.MasterSqlMapper;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 主库数据源配置类
 *
 * @author skyrock
 */
@Configuration
@MapperScan(basePackages = {"cn.sytton.**.mapper"}, //标准产品mapper路径，项目级mapper路径
        markerInterface = MasterSqlMapper.class,
        sqlSessionFactoryRef = "masterSqlSessionFactory")
public class DataSourceMaster {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "db.master")
    public DataSource masterDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        dataSource.setName(DataSourceType.MASTER.name());
        druidProperties.setProperties(dataSource);
        return dataSource;
    }

    @Primary
    @Bean
    public DatabaseIdProvider masterDatabaseIdProvider() {
        return DataSourcePropertiesBuilder.newDatabaseIdProvider();
    }

    @Bean
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource,
                                                  @Qualifier("masterDatabaseIdProvider") DatabaseIdProvider databaseIdProvider) throws Exception {
        return DataSourcePropertiesBuilder.newSqlSessionFactory(dataSource, databaseIdProvider, "classpath*:/mapper/*.xml");
    }

    @Bean
    @Primary
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean
    @Primary
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

}


